package app

import (
	"chat-app/internal/app/handlers"
	"chat-app/internal/app/middleware"
	"chat-app/internal/app/services"
	"chat-app/internal/app/ws"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func SetupRoutes(router *gin.Engine, db *gorm.DB, wsMgr *ws.Manager) {
	authService := services.NewAuthService(db)
	authHandler := handlers.NewAuthHandler(authService)

	authGroup := router.Group("/auth")
	{
		authGroup.POST("/register", authHandler.RegisterHandler) // 用户注册
		authGroup.POST("/login", authHandler.LoginHandler)       // 用户登录
	}
	// 初始化服务
	userService := services.NewUserService(db)

	// 用户相关处理器
	userHandler := handlers.NewUserHandler(userService)

	// 用户路由组
	userGroup := router.Group("/users")
	userGroup.Use(middleware.AuthMiddleware(authService)) // 需要认证中间件
	{
		userGroup.GET("/:userID", userHandler.GetUserInfo)                     // 获取用户信息
		userGroup.GET("/search", userHandler.SearchUsers)                      // 搜索用户
		userGroup.PUT("/nickname", userHandler.UpdateNickname)                 // 更新昵称
		userGroup.GET("/friend-status/:targetID", userHandler.GetFriendStatus) // 获取好友状态
	}

	// 在 SetupRoutes 函数中添加
	chatService := services.NewChatService(db)
	chatHandler := handlers.NewChatHandler(chatService)

	// API 路由组 - 需要认证的端点
	apiGroup := router.Group("/api")
	apiGroup.Use(middleware.AuthMiddleware(authService)) // 应用认证中间件
	{

		apiGroup.GET("/ws", wsMgr.HandleRequest)

		// 好友相关路由
		friendHandler := handlers.NewFriendHandler(services.NewFriendService(db))
		apiGroup.POST("/friends/:targetID", friendHandler.SendFriendRequest)
		apiGroup.GET("/friends/requests", friendHandler.GetFriendRequests)
		apiGroup.PUT("/friends/requests/:requestID", friendHandler.RespondToFriendRequest)
		apiGroup.GET("/friends/list", friendHandler.GetFriendList)
		apiGroup.DELETE("/friends/:friendID", friendHandler.RemoveFriend)

		// 私聊路由
		apiGroup.POST("/chat/private/:recipientID", chatHandler.SendPrivateMessage)
		apiGroup.GET("/chat/private/:recipientID/history", chatHandler.GetPrivateHistory)

		// 群聊路由
		apiGroup.POST("/chat/groups", chatHandler.CreateGroup)
		apiGroup.POST("/chat/groups/:groupID/members/:userID", chatHandler.AddGroupMember)
		apiGroup.DELETE("/chat/groups/:groupID/members/:userID", chatHandler.RemoveGroupMember)
		apiGroup.POST("/chat/groups/:groupID/messages", chatHandler.SendGroupMessage)
		apiGroup.GET("/chat/groups/:groupID/history", chatHandler.GetGroupHistory)

		// 消息管理
		apiGroup.DELETE("/chat/messages/:messageID", chatHandler.DeleteMessage)
		apiGroup.PUT("/chat/messages/:messageID/recall", chatHandler.RecallMessage)
	}

}
